package cn.xpf.study.service;

import cn.xpf.study.dao.LessonItemMapper;
import cn.xpf.study.dao.LessonMapper;
import cn.xpf.study.dao.LessonVideoMapper;
import cn.xpf.study.model.Lesson;
import cn.xpf.study.model.LessonItem;
import cn.xpf.study.model.vo.LessonVo;
import cn.xpf.study.utils.JsonUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * Create on 2021/5/15
 *
 * @author shuxinsheng@qiyi.com
 **/
@Service
public class LessonService {

    @Autowired
    LessonMapper lessonMapper;
    @Autowired
    LessonItemMapper lessonItemMapper;

    public void createLesson(LessonVo lessonVo) {
        Lesson lesson = new Lesson();
        lesson.id = lessonVo.id;
        lesson.name = lessonVo.name;
        lesson.order = lessonVo.order;
        lesson.title = lessonVo.title;
        lesson.desc = lessonVo.desc;
        lesson.image = lessonVo.image;
        lessonMapper.insertOne(lesson);
        updateLessonItem(lessonVo);
    }

    public void updateLesson(LessonVo lessonVo) {
        Lesson lesson = new Lesson();
        lesson.id = lessonVo.id;
        lesson.status = lessonVo.status;
        lesson.name = lessonVo.name;
        lesson.order = lessonVo.order;
        lesson.title = lessonVo.title;
        lesson.desc = lessonVo.desc;
        lesson.image = lessonVo.image;
        lessonMapper.updateOne(lesson);
        updateLessonItem(lessonVo);
    }

    public void updateLessonItem(LessonVo lessonVo) {
        LessonItem lessonItem = lessonItemMapper.findOne(lessonVo.id);
        if (lessonItem == null) {
            lessonItem = new LessonItem();
            lessonItem.setLessonId(lessonVo.id);
            lessonItem.setContent(JsonUtil.contentToJson(lessonVo.getContent()));
            lessonItemMapper.insertOne(lessonItem);
        } else {
            lessonItem.setContent(JsonUtil.contentToJson(lessonVo.getContent()));
            lessonItemMapper.updateOne(lessonItem);
        }
    }

}
